package com.kx.center.task;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.apache.commons.lang.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Service;

import com.kx.center.entity.TradeDetail;
import com.kx.center.entity.huiyin.Product;
import com.kx.center.entity.huiyin.SaleOrderItems;
import com.kx.center.service.TradeDetailService;
import com.kx.center.util.HttpClientUtil;
import com.kx.center.util.JSONParser;
import com.kx.center.util.SQLHelper;
import com.kx.center.util.StringUtil;

@Service
public class TransferTradeDetialTask {

	public static void main(String[] args) {
		ApplicationContext ac = new ClassPathXmlApplicationContext(
				"applicationContext.xml");
		TransferTradeDetialTask tt = ac.getBean(TransferTradeDetialTask.class);
		tt.execute();
	}

	@Autowired
	private TradeDetailService tradeDetailService;

	public void execute() {

		System.out.println(new Date() + "订单详情数据开始对接");

		// 获取慧银erp_sale_order_items
		try {
			Long l = null;
			if (tradeDetailService.saleOrderItemsMaxTime() == null) {
				l = 1446307200000L;
			} else {
				l = tradeDetailService.saleOrderItemsMaxTime();
			}
			HashMap<String, String> opts = new HashMap<String, String>();
			opts.put("mid", "100100210000038");
			opts.put("lastReceivedTime", l.toString());
			opts.put("count", "10000");
			opts.put("tableName", "erp_sale_order_items");
			String data = JSONParser.stringify(opts);
			String url = "http://cashier.91huishang.com//wizarposOpen-server/v1_0/saleData/getdata";

			String json = HttpClientUtil.post(url, data);
			@SuppressWarnings("unchecked")
			HashMap<String, Object> hashmap = (HashMap<String, Object>) JSONParser
					.parse(json, new HashMap<String, Object>().getClass());
			@SuppressWarnings("unchecked")
			List<HashMap<String, Object>> list = (List<HashMap<String, Object>>) hashmap
					.get("saleOrderItemList");
			for (HashMap<String, Object> map : list) {
				SaleOrderItems saleOrderItems = new SaleOrderItems();
				saleOrderItems.setId(map.get("id").toString().trim());
				saleOrderItems
						.setOrderId(map.get("order_id").toString().trim());
				saleOrderItems.setProductId(map.get("product_id").toString()
						.trim());
				saleOrderItems.setQty(NumberUtils.toInt(map.get("qty")
						.toString().trim()));
				saleOrderItems.setPrice(NumberUtils.toDouble(map.get("price")
						.toString().trim()) / 100);
				saleOrderItems.setRealPrice(NumberUtils.toDouble(map
						.get("real_price").toString().trim()) / 100);
				saleOrderItems.setAmount(NumberUtils.toDouble(map.get("amount")
						.toString().trim()) / 100);
				saleOrderItems.setRemark(StringUtil
						.checkString((String) map.get("remark")).toString()
						.trim());
				saleOrderItems.setLastTime(NumberUtils.toLong(map
						.get("last_time").toString().trim()));
				tradeDetailService.insertSaleOrderItems(saleOrderItems);
			}
		} catch (Exception e) {
			System.out.println(e);
		}

		// 获取慧银erp_product
		try{
			HashMap<String, String> opts = new HashMap<String, String>();
			opts.put("mid", "100100210000038");
			opts.put("lastReceivedTime", "");
			opts.put("count", "10000");
			opts.put("tableName", "erp_product");
			String data = JSONParser.stringify(opts);
			String url = "http://cashier.91huishang.com//wizarposOpen-server/v1_0/saleData/getdata";

			String json = HttpClientUtil.post(url, data);
			@SuppressWarnings("unchecked")
			HashMap<String, Object> hashmap = (HashMap<String, Object>) JSONParser
					.parse(json, new HashMap<String, Object>().getClass());
			@SuppressWarnings("unchecked")
			List<HashMap<String, Object>> list = (List<HashMap<String, Object>>) hashmap
					.get("productDataList");
			List<String> idList = tradeDetailService.findProductIdList();
			for (HashMap<String, Object> map : list) {
				if(!idList.contains(map.get("id").toString().trim())){
					Product product = new Product();
					product.setId(map.get("id").toString().trim());
					product.setCode(map.get("code").toString().trim());
					product.setCategoryId(map.get("category_id").toString().trim());
					product.setName(map.get("name").toString().trim());
					product.setUnit(map.get("unit").toString().trim());
					product.setPrice(NumberUtils.toDouble(map.get("price")
							.toString().trim()) / 100);
					product.setLastTime(NumberUtils.toLong(map.get("last_time")
							.toString().trim()));
					tradeDetailService.insertProduct(product);
				}else{
					Product product = new Product();
					product.setId(map.get("id").toString().trim());
					product.setCode(map.get("code").toString().trim());
					product.setCategoryId(map.get("category_id").toString().trim());
					product.setName(map.get("name").toString().trim());
					product.setUnit(map.get("unit").toString().trim());
					product.setPrice(NumberUtils.toDouble(map.get("price")
							.toString().trim()) / 100);
					product.setLastTime(NumberUtils.toLong(map.get("last_time")
							.toString().trim()));
					tradeDetailService.updateProduct(product);
				}
			}
		} catch (Exception e) {
			System.out.println(e);
		}
		System.out.println(new Date() + "产品表更新完成");

		// 写入odb订单tradeDetail表
		List<TradeDetail> lists = tradeDetailService.findTradeDetailList();
		List<String> s = tradeDetailService.findTradeDetailIdList();
		for (TradeDetail t : lists) {
			if (!s.contains(t.getOuterId())) {
				TradeDetail tradeDetail = new TradeDetail();
				tradeDetail.setOuterId(t.getOuterId());
				tradeDetail.setGoodsName(t.getGoodsName());
				tradeDetail.setGoodsNum(t.getGoodsNum());
				tradeDetail.setGoodsPrice(t.getGoodsPrice());
				tradeDetail.setGoodsPayPrice(t.getGoodsPayPrice());
				tradeDetail.setBundleSku(t.getBundleSku());
				tradeDetail.setGoodsId(t.getGoodsId());
				tradeDetail.setGoodsSku(t.getGoodsSku());
				tradeDetail.setStoreId(t.getStoreId());
				tradeDetail.setChannelId(2);
				tradeDetailService.insertTradeDetail(tradeDetail);
			}
		}
		System.out.println(new Date() + "订单详情数据对接完成");
		//更新trade_detail的trade_id
		String sql01 = "UPDATE trade_detail t_d JOIN trade t_t ON t_d.outer_id = t_t.outer_id "
				+ "SET t_d.trade_id = t_t.trade_id WHERE t_d.channel_id = 2";
		SQLHelper.executeUpdate(sql01, null, SQLHelper.odb);
		//更新库存
		String sql02 = "CREATE TABLE IF NOT EXISTS store_goods_temp2 LIKE store_goods ";
		SQLHelper.executeUpdate(sql02, null, SQLHelper.odb);
		//清空临时表
		String sql03 = "delete from store_goods_temp2";
		SQLHelper.executeUpdate(sql03, null, SQLHelper.odb);
		//查询各门店销售额及商品id到临时表中
		String sql04 = "INSERT INTO store_goods_temp2(store_id,goods_id,storage) "
				+ "SELECT t.store_id,t_d.goods_id, SUM(t_d.goods_num) selled_quantity "
				+ " FROM trade t JOIN trade_detail t_d ON t_d.outer_id = t.outer_id "
				+ "WHERE TO_DAYS(FROM_UNIXTIME(t.add_time)) = TO_DAYS(now()) "
				+ "AND t.channel_id = 2  GROUP BY goods_id,t.store_id ";
		SQLHelper.executeUpdate(sql04, null, SQLHelper.odb);
		
		//执行更新
		String sql05 = "UPDATE store_goods s_g JOIN store_goods_temp2 s_g_t "
				+ "ON s_g.goods_id = s_g_t.goods_id AND s_g.store_id = s_g_t.store_id "
				+ "SET s_g.ref_storage = (s_g.storage - s_g_t.storage)";
		SQLHelper.executeUpdate(sql05, null, SQLHelper.odb);
//		清空临时表
		SQLHelper.executeUpdate(sql03, null, SQLHelper.odb);
		System.out.println(new Date() + "库存更新成功");
	}
}
